package com.lzs.adx.web.modules.adx.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzs.adx.commmon.constant.Constant;
import com.lzs.adx.commmon.page.PageData;
import com.lzs.adx.commmon.utils.Result;
import com.lzs.adx.commmon.validator.AssertUtils;
import com.lzs.adx.commmon.validator.ValidatorUtils;
import com.lzs.adx.commmon.validator.group.AddGroup;
import com.lzs.adx.commmon.validator.group.DefaultGroup;
import com.lzs.adx.commmon.validator.group.UpdateGroup;
import com.lzs.adx.web.commmon.annotation.LogOperation;
import com.lzs.adx.web.commmon.utils.ExcelUtils;
import com.lzs.adx.web.modules.adx.dao.ReportDao;
import com.lzs.adx.web.modules.adx.dto.AccountDTO;
import com.lzs.adx.web.modules.adx.dto.MonitorTemplateDTO;
import com.lzs.adx.web.modules.adx.dto.ReportDTO;
import com.lzs.adx.web.modules.adx.entity.AccountEntity;
import com.lzs.adx.web.modules.adx.entity.MonitorTemplateEntity;
import com.lzs.adx.web.modules.adx.entity.ReportEntity;
import com.lzs.adx.web.modules.adx.excel.AccountExcel;
import com.lzs.adx.web.modules.adx.service.AccountService;
import com.lzs.adx.web.modules.adx.service.MonitorTemplateService;
import com.lzs.adx.web.modules.adx.service.ReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 投放的账户管理
 *
 * @author wangzhijun 825400558@qq.com
 * @since 1.0.0 2023-11-29
 */
@RestController
@RequestMapping("adx/account")
@Api(tags="投放的账户管理")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private MonitorTemplateService monitorTemplateService;


    @Autowired
    private ReportDao reportDao;



    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("adx:account:page")
    public Result<PageData<AccountDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<AccountDTO> page = accountService.page(params);

        return new Result<PageData<AccountDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("adx:account:info")
    public Result<AccountDTO> get(@PathVariable("id") String id){
        AccountDTO data = accountService.getDetail(id);
        if(StringUtils.isNotBlank(data.getSspExtend())){
            JSONObject jsonObject = JSONObject.parseObject(data.getSspExtend());
            if(jsonObject.containsKey("per")){
                data.setPer(jsonObject.getDouble("per"));
            }
        }
        return new Result<AccountDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("adx:account:save")
    public Result save(@RequestBody AccountDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        if(StringUtils.isNotBlank(dto.getDspReportUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspReportUrl());
            dto.setDspReportUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getDspCallbackUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspCallbackUrl());
            dto.setDspCallbackUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getDspReportClickUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspReportClickUrl());
            dto.setDspReportClickUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getDspReportImpUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspReportImpUrl());
            dto.setDspReportImpUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getSspExtend())) {
            String getSspExtend = StringEscapeUtils.unescapeHtml4(dto.getSspExtend());
            dto.setSspExtend(getSspExtend);
        }
        if(StringUtils.isNotBlank(dto.getDspExtend())) {
            String getDspExtend = StringEscapeUtils.unescapeHtml4(dto.getDspExtend());
            dto.setDspExtend(getDspExtend);
        }

        if(Objects.nonNull(dto.getPer())){
            JSONObject jsonObject=JSONObject.parseObject(dto.getSspExtend());
            jsonObject.remove("per");
            jsonObject.put("per",dto.getPer());
            dto.setSspExtend(jsonObject.toJSONString());
        }

        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        accountService.save(dto);

        HttpUtil.get("https://capi.qgxf.com.cn/common/sysnCacheToDb");

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("adx:account:update")
    public Result update(@RequestBody AccountDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);


        if(StringUtils.isNotBlank(dto.getDspReportUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspReportUrl());
            dto.setDspReportUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getDspCallbackUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspCallbackUrl());
            dto.setDspCallbackUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getDspReportClickUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspReportClickUrl());
            dto.setDspReportClickUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getDspReportImpUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getDspReportImpUrl());
            dto.setDspReportImpUrl(dspReportUrl);
        }
        if(StringUtils.isNotBlank(dto.getSspExtend())) {
            String getSspExtend = StringEscapeUtils.unescapeHtml4(dto.getSspExtend());
            dto.setSspExtend(getSspExtend);
        }
        if(StringUtils.isNotBlank(dto.getDspExtend())) {
            String getDspExtend = StringEscapeUtils.unescapeHtml4(dto.getDspExtend());
            dto.setDspExtend(getDspExtend);
        }

        //扣回传功能
        if(Objects.nonNull(dto.getPer())){
            JSONObject jsonObject=JSONObject.parseObject(dto.getSspExtend());
            jsonObject.remove("per");
            jsonObject.put("per",dto.getPer());
            dto.setSspExtend(jsonObject.toJSONString());
        }


        accountService.update(dto);

        HttpUtil.get("https://capi.qgxf.com.cn/common/sysnCacheToDb");

        return new Result();
    }


    @GetMapping("generateUrl")
    public Result generateUrl(String id,String templateId){


        MonitorTemplateEntity monitorTemplateEntity = monitorTemplateService.selectById(templateId);
        String format = String.format(monitorTemplateEntity.getClickUrl(), id);
        return new Result().ok(format);
    }


    @GetMapping("copy")
    public Result copy(String id){
        AccountDTO detail = accountService.getDetail(id);
        detail.setId(null);
        detail.setCreateTime(new Date());
        detail.setUpdateTime(new Date());
        accountService.save(detail);
        return new Result().ok();
    }


    @GetMapping("send")
    public Result send(String id,String templateId){

        Map<String,Object> params=new HashMap<>();
        params.put("dspId",id);
        params.put("day", DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));

        LambdaQueryWrapper<ReportEntity> lambdaQueryWrappe=new LambdaQueryWrapper<>();
        lambdaQueryWrappe.eq(ReportEntity::getDspId,id);
        lambdaQueryWrappe.eq(ReportEntity::getDay,id);
        lambdaQueryWrappe.orderByDesc(ReportEntity::getCreateTime);
        lambdaQueryWrappe.last("limit 1");
        List<ReportEntity> reportEntities = reportDao.selectList(lambdaQueryWrappe);
        if(CollectionUtil.isEmpty(reportEntities)){
            return new Result(100,"未找到上报的请求");
        }
        ReportEntity reportEntity = reportEntities.get(0);
        if(StringUtils.isBlank(reportEntity.getOaid()) && StringUtils.isBlank("reportEntity.getImei()")){
            return new Result(101,"未获取设备信息，请打开手机权限，或者切换安卓设备");
        }

        AccountEntity accountEntity = accountService.selectById(id);

        String url=null;
        if(accountEntity.getProduct().equals("elm")|| accountEntity.getProduct().equals("xhs")) {
            MonitorTemplateEntity monitorTemplateEntity = monitorTemplateService.selectById(templateId);
            url=String.format(monitorTemplateEntity.getCallbackUrl(), id,System.currentTimeMillis());
        }
        return new Result().ok(url);

    }


    @GetMapping("templateList")
    public Result getMonitorTemplateList(){
        List<MonitorTemplateDTO> list = monitorTemplateService.list(new HashMap<>());
        return new Result().ok(list);
    }


    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("adx:account:delete")
    public Result delete(@RequestBody String[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        accountService.deleteByIds(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("adx:account:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<AccountDTO> list = accountService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, AccountExcel.class);
    }

}